package com.zhanghe.study.java8.stream;

import java.util.*;

/**
 * 排序
 */
public class TestStreamApi2 {
    private static List<User> list = new ArrayList<>(
            Arrays.asList(
                    new User(1,"张三",18, (byte) 0),
                    new User(2,"李四",20, (byte) 1),
                    new User(3,"王五",16, (byte) 0),
                    new User(4,"赵六",25, (byte) 1),
                    new User(5,"张三",30, (byte) 0),
                    new User(6,"张三",8, (byte) 0)
            )
    );
    public static void main(String[] args) {
        System.out.println("========test自然排序======");
        test();
        System.out.println("========test1自然排序======");
        test1();
    }

    /**
     * sorted()自然排序  Comparable 所要排序的类必须实现Comparable接口
     */
    public static void test(){
        list.stream().map(User::getAge).sorted().forEach(System.out::println);
    }

    /**
     * sorted(Comparator com) 定制排序(Comparator)
     */
    public static void test1(){
        list.stream().sorted(
                (o1, o2) -> {
                    if(o1.getAge() > o2.getAge()){
                        return -1;
                    }
                    return 0;
                }
        ).forEach(System.out::println);
    }

    static class User{
        private long id;
        private String name;
        private int age;
        private byte sex;

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    ", sex=" + sex +
                    '}';
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            User user = (User) o;
            return id == user.id &&
                    age == user.age &&
                    sex == user.sex &&
                    Objects.equals(name, user.name);
        }

        @Override
        public int hashCode() {
            return Objects.hash(id, name, age, sex);
        }

        public User(long id, String name, int age, byte sex){
            this.id = id;
            this.name = name;
            this.age = age;
            this.sex = sex;
        }

        public long getId() {
            return id;
        }

        public void setId(long id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public byte getSex() {
            return sex;
        }

        public void setSex(byte sex) {
            this.sex = sex;
        }
    }
}
